﻿using System;
using System.Collections.Generic;
using System.Text;
using AgencyManagerSystem.Model;
using AgencyManagerSystem.Common;
using Dapper;
using System.Linq;

namespace AgencyManagerSystem.DataFetcher
{
    public class ModuleFetcher : BaseFetcher<ModuleModel>
    {
        public ModuleFetcher() : base()
        {

        }
        public ModuleModel GetByCode(string code)
        {
            Condition[] conditions = new Condition[] { new Condition() { Key = "Code", Op = "=", Value = code } };
            var list = List(conditions);
            if (list.Count > 0)
                return list.First();
            else
                return null;
        }
        public override void AddDefaultFilter(StringBuilder stringBuilder, DynamicParameters dynamicParameters)
        {
            //任何时候都要让所有人查询模块信息
            //base.AddDefaultFilter(stringBuilder, dynamicParameters);
        }
        public IList<ModuleModel> ListByUser(int userid, int domain)
        {
            string sqlCheckIfAdm = String.Format("SELECT COUNT(*) FROM SYS_ROLEUSER WHERE AUTOID = 1 AND USER = {0} AND DOMAIN = {1}", userid, domain);
            long roles = (Int64)DBHelper.GetTran().ExecuteScalar<Int32>(sqlCheckIfAdm );
            string sqlstr = String.Format("SELECT * FROM SYS_MODULE WHERE AUTOID IN (SELECT MODULE FROM SYS_ROLETABLE WHERE ROLE IN (SELECT ROLE FROM SYS_ROLEUSER WHERE USER = {0} AND DOMAIN = {1}))", userid, domain);
            if (roles > 0)
            {
                return List();
            }
            else
            {
                return DBHelper.GetTran().Query<ModuleModel>(sqlstr).ToList();
            }
        }

        public IList<ModuleWithRoleModel> ListByUserWithRole(int userid, int domain)
        {
            //string sqlstr = String.Format("SELECT B.*,IFNULL(A.EXEC,TRUE) AS EXEC,IFNULL(A.CREATE,TRUE) AS `CREATE`,IFNULL(A.MODIFY,TRUE) AS `MODIFY`,IFNULL(A.DELETE,TRUE) AS `DELETE`,IFNULL(A.APPROVE,TRUE) AS APPROVE,IFNULL(A.UNAPPROVE,TRUE) AS UNAPPROVE,IFNULL(A.FUNC1,TRUE) AS FUNC1,IFNULL(A.FUNC2,TRUE) AS FUNC2,IFNULL(A.FUNC3,TRUE) AS FUNC3,IFNULL(A.FUNC4,TRUE) AS FUNC4 FROM SYS_ROLETABLE A RIGHT JOIN SYS_MODULE B ON  A.MODULE = B.AUTOID WHERE EXISTS (SELECT 1 FROM SYS_ROLEUSER C WHERE (USER = {0} AND DOMAIN = {1}) AND (C.ROLE = A.ROLE OR C.AUTOID=1))", userid, domain);
            string sqlstr = String.Format("SELECT B.*,A.CREATE,A.APPROVE,A.DELETE,A.UNAPPROVE,A.FUNC1,A.FUNC2,A.FUNC3,A.FUNC4 FROM SYS_ROLETABLE A RIGHT JOIN SYS_MODULE B ON  A.MODULE = B.AUTOID WHERE EXISTS (SELECT 1 FROM SYS_ROLEUSER C WHERE (USER = {0} AND DOMAIN = {1}) AND C.ROLE = A.ROLE)", userid, domain);

            return DBHelper.GetTran().Query<ModuleWithRoleModel>(sqlstr).ToList();

        }
    }
}
